package com.bjut.vendormgrsys.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;


public class HttpUtil {

    private final static Logger logger = LoggerFactory.getLogger(HttpUtil.class);




    public static String doPost(String url,String json,Map<String, String> header) {
        try {
            //1.获得一个httpclient对象
            CloseableHttpClient httpclient = HttpClients.createDefault();
            //2.生成一个post请求
            HttpPost httppost = new HttpPost(url);

            for (Map.Entry<String, String> entry : header.entrySet()) {
                //给参数赋值
                httppost.setHeader(entry.getKey(), entry.getValue());
            }

            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(100000)
                    .setConnectTimeout(100000)
                    .build();
            httppost.setConfig(requestConfig);

            CloseableHttpResponse response = null;
            try {
                StringEntity se = new StringEntity(json,"utf-8");
                httppost.setEntity(se);
                //3.执行get请求并返回结果
                response = httpclient.execute(httppost);
            } catch (IOException e) {
                e.printStackTrace();
            }
            //4.处理结果，这里将结果返回为字符串
            HttpEntity entity = response.getEntity();
            String result = null;
            try {
                result = EntityUtils.toString(entity);
            } catch (ParseException | IOException e) {
                e.printStackTrace();
            }
            return result;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }


    public static void main(String[] args) {
        String url = "https://spark-api-open.xf-yun.com/v1/chat/completions";
        Map<String,String> headers = new HashMap<>();
        headers.put("Content-Type","application/json");
        headers.put("Authorization","Bearer c76a8f98cbec7789ef918923d2b9b487:ODUyZTRlZmI0ZDA1OGRhMGYyOTg2MGY4");

        Map<String,Object> requests = new HashMap<>();
        requests.put("model","generalv3.5");//取值为[general,generalv2,generalv3,generalv3.5,4.0Ultra]
//        requests.put("stream",false);//是否开启流式传输,默认False
//        requests.put("temperature",0.5f);//取值范围 (0，1] ，默认值0.5	,核采样阈值。用于决定结果随机性，取值越高随机性越强即相同的问题得到的不同答案的可能性越高
//        requests.put("max_tokens",4096);//取值为[1,8192]，默认为4096。模型回答的tokens的最大长度
//        requests.put("top_k",4);//取值为[1，6],默认为4	,从k个候选中随机选择⼀个（⾮等概率）
        List<Map<String,String>> messages = new ArrayList<>();
        Map<String,String> mes = new HashMap<>();
        mes.put("role","user");//system用于设置对话背景，user表示是用户的问题，assistant表示AI的回复
        mes.put("content","给我生成一个户外交友活动安排");//所有content的累计tokens需控制8192以内
        messages.add(mes);
        requests.put("messages",messages);
        System.out.println(JSONObject.toJSONString(requests));
        String result = HttpUtil.doPost(url, JSONObject.toJSONString(requests),headers);
        System.out.println(result);
    }
}
